import java.util.ArrayList;
import java.util.List;

class Solution20 {
        public List<List<Integer>> ret;
        public List<Integer> path;
        public int aim;
        public List<List<Integer>> combinationSum(int[] candidates, int target) {
            aim = target;
            ret = new ArrayList<>();
            path = new ArrayList<>();
            dfs(candidates,0,0);
            return ret;
        }

        public void dfs(int[] candidates,int pos,int sum) {
            if(sum == aim) {
                ret.add(new ArrayList<>(path));
                return;
            }
            if(sum > aim || candidates.length == pos) return;
            for(int i = pos; i < candidates.length; i++) {
                path.add(candidates[i]);
                dfs(candidates,i,sum + candidates[i]);
                path.remove(path.size()-1);
            }
        }
    public void dfs1(int[] candidates,int pos,int sum) {
        if(sum == aim) {
            ret.add(new ArrayList<>(path));
            return;
        }
        if(sum > aim || pos == candidates.length) return;

        //枚举，candidates[pos]的个数
        for(int k = 0; k*candidates[pos] + sum <= aim; k++) {
            if(k != 0) path.add(candidates[pos]);
            dfs(candidates,pos+1,sum + k*candidates[pos]);
        }

        for(int k = 1; k*candidates[pos] + sum <= aim; k++) {
            path.remove(path.size()-1);
        }
    }
}